// 拦截fetch和XMLHttpRequest请求
// 通过注入script标签到页面上下文
(function() {
  'use strict';
  
  console.log('===== 网络请求拦截器已加载 =====');
  console.log('当前页面URL:', window.location.href);
  console.log('当前时间:', new Date().toISOString());
  
  // 测试 Chrome API 是否可用
  if (typeof chrome !== 'undefined' && chrome.runtime) {
    console.log('✅ Chrome Runtime API 可用');
  } else {
    console.error('❌ Chrome Runtime API 不可用');
  }
  
  // 获取拦截规则
  let interceptionRules = [
    {
      id: 'rule_1',
      name: '🏦 杭州银行流水',
      urlPattern: '/uc-server/service/hzDealDetailReport/hzDealDetailQuery',
      matchType: 'includes',
      method: '',
      apiEndpoint: 'http://127.0.0.1:9001/api/v1/plugin/data/receive',
      dataType: 'bank',
      enabled: true
    },
    {
      id: 'rule_2',
      name: '📦 政采云订单',
      urlPattern: '/api/mall/order/list',
      matchType: 'exact',
      method: 'POST',
      apiEndpoint: 'http://127.0.0.1:9001/api/v1/plugin/data/receive',
      dataType: 'sales_order', // 销售订单
      enabled: true
    },
    {
      id: 'rule_3',
      name: '📢 政采云公告',
      urlPattern: '/announcement/lobby/queryPage',
      matchType: 'includes',
      method: '',
      apiEndpoint: 'http://127.0.0.1:9001/api/v1/plugin/data/receive',
      dataType: 'announcement',
      enabled: true
    },
    {
      id: 'rule_4',
      name: '📥 进项发票',
      urlPattern: '/szzhzz/qlfpcx/v1/queryFpjcxx',
      matchType: 'includes',
      method: 'POST',
      apiEndpoint: 'http://127.0.0.1:9001/api/v1/plugin/data/receive',
      dataType: 'incoming_invoice',
      enabled: true
    },
    {
      id: 'rule_5',
      name: '📤 销项发票',
      urlPattern: '/szzhzz/fpxxcx/v1/queryFpxx',
      matchType: 'includes',
      method: 'POST',
      apiEndpoint: 'http://127.0.0.1:9001/api/v1/plugin/data/receive',
      dataType: 'outgoing_invoice',
      enabled: true
    },
    {
      id: 'rule_6',
      name: '🛒 采购订单',
      urlPattern: '/api/purchase/order/list',
      matchType: 'exact',
      method: 'POST',
      apiEndpoint: 'http://127.0.0.1:9001/api/v1/plugin/data/receive',
      dataType: 'purchase_order', // 采购订单
      enabled: true
    }
  ];
  
  // 从存储中获取自定义规则
  chrome.storage.local.get(['interceptionRules'], (result) => {
    console.log('🔧 从存储中获取拦截规则:', result);
    if (result && result.interceptionRules) {
      // 检查是否为数组格式
      if (Array.isArray(result.interceptionRules)) {
        interceptionRules = result.interceptionRules;
        console.log('🔧 已加载自定义拦截规则:', interceptionRules.length, '条');
      } else if (typeof result.interceptionRules === 'object') {
        // 如果是对象格式，转换为数组
        const rulesArray = Object.values(result.interceptionRules);
        if (Array.isArray(rulesArray)) {
          interceptionRules = rulesArray;
          console.log('🔧 已加载自定义拦截规则(对象格式已转换):', interceptionRules.length, '条');
        } else {
          console.log('ℹ️ 未找到自定义规则，使用默认规则');
        }
      } else {
        console.warn('⚠️ 拦截规则格式不正确:', result.interceptionRules);
      }
      
      // 详细输出每条规则
      console.log('📋 当前拦截规则详情:');
      interceptionRules.forEach((rule, index) => {
        console.log(`  ${index + 1}. ${rule.name || '未命名规则'}:`);
        console.log(`     - URL模式: ${rule.urlPattern}`);
        console.log(`     - 匹配类型: ${rule.matchType || 'includes'}`);
        console.log(`     - HTTP方法: ${rule.method || 'ALL'}`);
        console.log(`     - API端点: ${rule.apiEndpoint}`);
        console.log(`     - 启用状态: ${rule.enabled !== false ? '启用' : '禁用'}`);
      });
      
      // 同时发送加载的规则到页面上下文
      setTimeout(() => {
        if (interceptionRules && interceptionRules.length > 0) {
          console.log('📤 发送加载的规则到页面上下文:', interceptionRules);
          window.postMessage({
            type: 'LX_PLUGIN_RULES_UPDATE',
            rules: interceptionRules.map(rule => ({
              urlPattern: rule.urlPattern,
              method: rule.method || '',
              matchType: rule.matchType || 'includes',
              dataType: rule.dataType || 'other',  // 添加数据类型字段
              enabled: rule.enabled !== false,  // 添加启用状态
              captureHtml: rule.captureHtml || false,  // 添加捕获HTML字段
              extractShopId: rule.extractShopId || false,  // 添加提取ShopId字段
              targetShopIds: rule.targetShopIds || []  // 添加目标ShopId列表字段
            }))
          }, '*');
        }
      }, 100);
    } else {
      console.log('ℹ️ 未找到自定义规则，使用默认规则');
    }
  });

  // 监听存储变化，及时更新拦截规则
  chrome.storage.onChanged.addListener((changes, areaName) => {
    if (areaName === 'local' && changes.interceptionRules) {
      console.log('🔄 拦截规则已更新:', changes.interceptionRules.newValue);
      if (changes.interceptionRules.newValue && Array.isArray(changes.interceptionRules.newValue)) {
        interceptionRules = changes.interceptionRules.newValue;
        console.log('✅ 已更新拦截规则:', interceptionRules.length, '条');
        // 详细输出每条规则
        console.log('📋 更新后的拦截规则详情:');
        interceptionRules.forEach((rule, index) => {
          console.log(`  ${index + 1}. ${rule.name || '未命名规则'}:`);
          console.log(`     - URL模式: ${rule.urlPattern}`);
          console.log(`     - 匹配类型: ${rule.matchType || 'includes'}`);
          console.log(`     - HTTP方法: ${rule.method || 'ALL'}`);
          console.log(`     - API端点: ${rule.apiEndpoint}`);
          console.log(`     - 启用状态: ${rule.enabled !== false ? '启用' : '禁用'}`);
        });
        
        // 同时发送更新后的规则到页面上下文
        setTimeout(() => {
          if (interceptionRules && interceptionRules.length > 0) {
            console.log('📤 发送更新后的规则到页面上下文:', interceptionRules);
            window.postMessage({
              type: 'LX_PLUGIN_RULES_UPDATE',
              rules: interceptionRules.map(rule => ({
                urlPattern: rule.urlPattern,
                method: rule.method || '',
                matchType: rule.matchType || 'includes',
                dataType: rule.dataType || 'other',  // 添加数据类型字段
                enabled: rule.enabled !== false,  // 添加启用状态
                captureHtml: rule.captureHtml || false,  // 添加捕获HTML字段
                extractShopId: rule.extractShopId || false,  // 添加提取ShopId字段
                targetShopIds: rule.targetShopIds || []  // 添加目标ShopId列表字段
              }))
            }, '*');
          }
        }, 100);
      }
    }
  });

  // URL匹配函数
  function isUrlMatch(url, pattern, matchType) {
    // 如果没有指定匹配类型，默认使用includes
    if (!matchType || matchType === 'includes') {
      return url.includes(pattern);
    }
    
    // 精确匹配
    if (matchType === 'exact') {
      // 移除查询参数后进行精确匹配
      const urlWithoutQuery = url.split('?')[0];
      return urlWithoutQuery === pattern;
    }
    
    // 前缀匹配
    if (matchType === 'startsWith') {
      return url.startsWith(pattern);
    }
    
    // 后缀匹配
    if (matchType === 'endsWith') {
      return url.endsWith(pattern);
    }
    
    // 正则表达式匹配
    if (matchType === 'regex') {
      try {
        const regex = new RegExp(pattern);
        return regex.test(url);
      } catch (e) {
        console.error('❌ 正则表达式错误:', pattern, e);
        return false;
      }
    }
    
    // 默认使用includes
    return url.includes(pattern);
  }

  // 监听来自页面的消息
  window.addEventListener('message', function(event) {
    // 确保消息来源是同一个页面
    if (event.source !== window) return;
    
    if (event.data.type === 'INTERCEPTED_REQUEST') {
      console.log('📨 收到页面拦截的请求数据');
      const requestData = event.data.data;
      
      // 添加调试信息
      console.log('🔍 处理拦截请求:', requestData.url, 'Method:', requestData.method);
      
      // 根据配置的规则发送到不同的 API
      let apiEndpoint = '';
      let matchedRule = null;
      for (const rule of interceptionRules) {
        if (rule.enabled !== false && 
            isUrlMatch(requestData.url, rule.urlPattern, rule.matchType) && 
            (!rule.method || rule.method === requestData.method)) {
          apiEndpoint = rule.apiEndpoint;
          matchedRule = rule;
          console.log('✅ 匹配到规则:', rule.name, '->', rule.urlPattern, 'Method:', rule.method || 'ALL', 'MatchType:', rule.matchType || 'includes');
          break;
        }
      }
      
      // 检查是否需要进行ShopId过滤
      let shouldSendToApi = true;
      if (matchedRule && matchedRule.extractShopId && requestData.shopIds && Array.isArray(requestData.shopIds)) {
        // 确保targetShopIds是数组格式
        let targetShopIdsArray = [];
        if (Array.isArray(matchedRule.targetShopIds)) {
          targetShopIdsArray = matchedRule.targetShopIds;
        } else if (matchedRule.targetShopIds && typeof matchedRule.targetShopIds === 'object') {
          targetShopIdsArray = Object.values(matchedRule.targetShopIds);
        }
        
        // 如果指定了目标ShopId，则检查当前请求的ShopId是否匹配
        if (targetShopIdsArray.length > 0) {
          // 检查是否有任何一个shopId在目标列表中
          let shopIdMatched = false;
          for (const shopId of requestData.shopIds) {
            if (targetShopIdsArray.includes(shopId.toString())) {
              shopIdMatched = true;
              break;
            }
          }
          
          // 如果没有匹配的ShopId，则不发送到API
          if (!shopIdMatched) {
            shouldSendToApi = false;
            console.log('ℹ️ ShopId不匹配目标列表:', requestData.shopIds.join(', '), '目标列表:', targetShopIdsArray.join(', '));
          } else {
            console.log('✅ ShopId匹配成功:', requestData.shopIds.join(', '));
          }
        }
      }
      
      // 如果匹配到目标 URL，并且满足ShopId过滤条件，则发送到对应的 API 端点
      if (apiEndpoint && shouldSendToApi) {
        console.log('🚀 发送数据到API端点:', apiEndpoint);
        // 如果需要捕获HTML，则获取当前页面的HTML内容
        if (matchedRule.captureHtml) {
          requestData.pageHtml = document.documentElement.outerHTML;
        }
        sendToApi(apiEndpoint, requestData, matchedRule.dataType, matchedRule.captureHtml, matchedRule.extractShopId);
      } else if (apiEndpoint && !shouldSendToApi) {
        console.log('ℹ️ ShopId不匹配，不发送到API端点:', apiEndpoint);
      } else {
        console.log('ℹ️ 未匹配到任何规则，不发送到API');
      }
      
      // 同时保存到 localStorage 作为备份
      saveToLocalStorage(requestData);
      
      // 发送到后台服务工作者保存数据
      try {
        if (chrome && chrome.runtime && chrome.runtime.sendMessage) {
          chrome.runtime.sendMessage({
            action: 'saveResponse',
            url: requestData.url,
            method: requestData.method,
            timestamp: requestData.timestamp,
            response: requestData.response,
            status: requestData.status,
            dataType: matchedRule ? (matchedRule.dataType || determineDataType(requestData.url)) : determineDataType(requestData.url),  // 添加数据类型字段
            shopIds: requestData.shopIds  // 添加shopIds字段
          }, (response) => {
            console.log('Background response:', response);
          });
        } else {
          console.warn('Chrome runtime is not available, skipping message send');
        }
      } catch (error) {
        console.error('Failed to send message to background:', error);
      }
    }
  });

  // 监听来自popup或options页面的消息
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === 'checkRulesUpdate') {
      // 重新从存储中获取规则
      chrome.storage.local.get(['interceptionRules'], (result) => {
        if (result && result.interceptionRules && Array.isArray(result.interceptionRules)) {
          interceptionRules = result.interceptionRules;
          console.log('🔧 手动更新拦截规则:', interceptionRules.length, '条');
          console.log('📋 当前拦截规则详情:', interceptionRules);
          sendResponse({success: true, message: '规则已更新'});
        } else {
          sendResponse({success: false, message: '未找到有效规则'});
        }
      });
      return true; // 保持消息通道开放以进行异步响应
    }
  });
  
  // 根据URL确定数据类型（大小写不敏感）
  function determineDataType(url, ruleDataType) {
    // 如果规则中指定了数据类型，优先使用规则中的类型
    if (ruleDataType) {
      return ruleDataType;
    }
    
    // 移除查询参数，只检查路径部分，并转换为小写进行比较
    const path = url.split('?')[0].toLowerCase();
    
    if (path.includes('bank') || path.includes('transaction') || path.includes('hzdealreport')) {
      return 'bank';
    } else if (path.includes('purchase') && path.includes('order')) {
      return 'purchase_order';
    } else if (path.includes('order') || path.includes('mall')) {
      return 'sales_order';
    } else if (path.includes('qlfpcx')) {
      // 进项发票查询接口
      return 'incoming_invoice';
    } else if (path.includes('fpxxcx')) {
      // 销项发票查询接口
      return 'outgoing_invoice';
    } else if (path.includes('invoice') || path.includes('fpjcxx')) {
      // 其他发票相关接口
      return 'invoice';
    } else if (path.includes('announcement') || path.includes('querypage')) {
      return 'announcement';
    }
    return 'unknown';
  }

  // 发送数据到 API
  function sendToApi(apiUrl, data, ruleDataType, captureHtml = false, extractShopId = false) {
    console.log('🚀 发送数据到:', apiUrl);
    
    // 确定数据类型
    const dataType = determineDataType(data.url, ruleDataType);
    
    // 构造符合新API格式的数据
    const pluginData = {
      batchId: 'batch_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
      timestamp: Date.now(), // 使用毫秒时间戳格式
      dataType: dataType,  // 使用确定的数据类型
      data: [{
        ...data,
        currentPageUrl: data.url || window.location.href,  // 添加当前页面的完整URL
        ruleInfo: {
          dataType: dataType  // 添加规则信息中的数据类型
        }
      }]
    };
    
    // 如果需要捕获页面HTML，则添加HTML内容
    if (captureHtml || data.pageHtml) {
      pluginData.pageHtml = data.pageHtml || document.documentElement.outerHTML;
    }
    
    // 如果需要提取ShopId，则添加shopIds
    if (extractShopId && data.shopIds && Array.isArray(data.shopIds)) {
      pluginData.shopIds = data.shopIds;
    }
    
    console.log('📤 准备发送的数据:', JSON.stringify(pluginData, null, 2));
    
    fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(pluginData)
    })
    .then(response => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
    })
    .then(result => {
      console.log('✅ 发送成功:', apiUrl);
      console.log('📥 API响应:', result);
    })
    .catch(error => {
      console.error('❌ 发送失败:', apiUrl, error);
      console.log('💾 失败的数据已保存到localStorage，可稍后重试');
    });
  }
  
  // 保存到 localStorage
  function saveToLocalStorage(data) {
    try {
      const key = `hzbank_${new Date().getTime()}`;
      const allData = JSON.parse(localStorage.getItem('hzbank_requests') || '[]');
      allData.push({
        key: key,
        timestamp: data.timestamp,
        url: data.url,
        data: data
      });
      
      // 只保留最近50条记录，避免超出存储配额
      if (allData.length > 50) {
        allData.splice(0, allData.length - 50);
      }
      
      localStorage.setItem('hzbank_requests', JSON.stringify(allData));
      console.log('💾 已保存到本地存储，共', allData.length, '条记录');
    } catch (e) {
      if (e.name === 'QuotaExceededError') {
        console.warn('⚠️ 本地存储配额已满，正在清理旧数据...');
        try {
          // 清理旧数据，只保留最近20条记录
          let reducedData = JSON.parse(localStorage.getItem('hzbank_requests') || '[]');
          if (reducedData.length > 20) {
            reducedData = reducedData.slice(-20);
            localStorage.setItem('hzbank_requests', JSON.stringify(reducedData));
            console.log('✅ 已清理旧数据，当前保留', reducedData.length, '条记录');
          } else {
            // 如果数据量不大但仍然超出配额，清空所有数据
            localStorage.removeItem('hzbank_requests');
            console.log('🗑️ 本地存储已清空');
          }
          
          // 再次尝试保存当前数据
          const key = `hzbank_${new Date().getTime()}`;
          let currentData = JSON.parse(localStorage.getItem('hzbank_requests') || '[]');
          currentData.push({
            key: key,
            timestamp: data.timestamp,
            url: data.url,
            data: data
          });
          
          // 确保不超过20条记录
          if (currentData.length > 20) {
            currentData.splice(0, currentData.length - 20);
          }
          
          localStorage.setItem('hzbank_requests', JSON.stringify(currentData));
          console.log('💾 数据已保存到本地存储，共', currentData.length, '条记录');
        } catch (cleanupError) {
          console.error('❌ 清理本地存储失败:', cleanupError);
        }
      } else {
        console.error('保存到本地存储失败:', e);
      }
    }
  }
  
  // 创建一个script元素，注入到页面上下文中
  const script = document.createElement('script');
  script.src = chrome.runtime.getURL('content/injected.js');
  script.onload = function() {
    this.remove();
    console.log('✅ 页面上下文脚本已注入');
    
    // 不再在这里发送规则，而是在存储加载完成后发送
  };
  script.onerror = function() {
    console.error('❌ 注入脚本加载失败');
  };
  (document.head || document.documentElement).appendChild(script);
})();